<!--
 * @Author: Li Zengkun
 * @Date: 2022-07-25 17:20:57
 * @LastEditors: Li Zengkun
 * @LastEditTime: 2022-08-18 14:24:13
 * @Description: 
-->
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="../css/reset.css">
    <link rel="stylesheet" href="../css/style.css">
    <link rel="stylesheet" href="../css/cart.css">
    <link rel="stylesheet" href="../node_modules/font-awesome/css/font-awesome.min.css">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>购物车</title>
</head>

<body>
    <header>
        <p></p>
        <p>
            购物车( <span id="total"></span> )
        </p>
        <p></p>
    </header>
    <div class="content-box">
        <ul id="goods-list" class="goods-list">



        </ul>

        <div class="guess-like">
            <div class="headline">猜你喜欢</div>
            <ul>
                <li>
                    <div class="img-box">
                        <img src="../img/cart/g (2).png" alt="">

                    </div>
                    <div class="title">清新四件套清新四件套清新四件套</div>
                    <div class="price">￥<span id="price">399</span></div>
                </li>
                <li>
                    <div class="img-box">
                        <img src="../img/cart/g (2).png" alt="">

                    </div>
                    <div class="title">清新四件套</div>
                    <div class="price">￥<span id="price">399</span></div>
                </li>
                <li>
                    <div class="img-box">
                        <img src="../img/cart/g (2).png" alt="">

                    </div>
                    <div class="title">清新四件套</div>
                    <div class="price">￥<span id="price">399</span></div>
                </li>
                <li>
                    <div class="img-box">
                        <img src="../img/cart/g (2).png" alt="">

                    </div>
                    <div class="title">清新四件套</div>
                    <div class="price">￥<span id="price">399</span></div>
                </li>
                <li>
                    <div class="img-box">
                        <img src="../img/cart/g (2).png" alt="">

                    </div>
                    <div class="title">清新四件套</div>
                    <div class="price">￥<span id="price">399</span></div>
                </li>

            </ul>
        </div>
    </div>


    <!-- 下单 -->
    <div class="place-order">
        <label for="checkAll">
            <input type="checkbox" id="checkAll">
            全选
        </label>
        <div class="price">￥<span id="sum-price"></span></div>
        <a id="create-order" class="btn">结 算</a>
    </div>

    <!-- 底部导航 -->
    <nav class="bottom-nav">
        <a href="./index.html">
            <img src="../img/footer/首页1.png" alt="">
            <span>首页</span>
        </a>
        <a href="./selection.html">
            <img src="../img/footer/钻石 (1).png" alt="">
            <span>优选</span>
        </a>
        <a href="./classify.html">
            <img src="../img/footer/分类2.png" alt="">
            <span>分类</span>
        </a>
        <a class="active" href="./cart.html">
            <img src="../img/footer/购物车1.png" alt="">
            <span>购物车</span>
        </a>
        <a href="./personal_center.html">
            <img src="../img/footer/我的2.png" alt="">
            <span>我的</span>
        </a>
    </nav>

    <!-- 加载中 -->
    <div class="loading">
        <img class="rotate-center" src="../img/loading.svg" alt="">
        <p>加载中...</p>
    </div>

    <!-- 提示 tip -->
    <span id="tip" class="tip"></span>
</body>


<script src="../js/axios.min.js"></script>
<script src="../js/axios_config.js"></script>
<script src="../js/api.js"></script>
<script>
    let oTotal = document.querySelector("#total")
    let oGoodsList = document.querySelector("#goods-list")
    let oAllCheckInput = document.querySelector("#checkAll")
    let oSumPrice = document.querySelector("#sum-price")
        // let oTip = document.querySelector('#tip')
    let oCreateOrderBtn = document.querySelector('#create-order')
    let oLoading = document.querySelector('.loading')


    let pageindex = 1;
    let pagesize = 10;
    let goods = [];
    let total = 0;

    init()

    /**
     * @description: 初始化
     * @return {*}
     */
    async function init() {
        // 获取全部购物车商品
        await getCartAll()
        console.log(goods);
        oTotal.innerHTML = total
        await initCartList()
        sumPrice()

        // 添加全选事件
        oAllCheckInput.addEventListener('click', () => {
            let oGoodsCheck = Array.from(document.querySelectorAll('.goods-check'))

            if (oAllCheckInput.checked) {
                // debounceThrottle(openTip('全选'), 3000)
                openTip("全选")
            }
            oGoodsCheck.forEach((element) => {
                element.checked = oAllCheckInput.checked
                if (element.checked) {
                    element.classList.add('ischeck')
                } else {
                    element.classList.remove('ischeck')
                }
            })
            sumPrice()
        })


        let oAllGoods = document.querySelectorAll('.good')
        oAllGoods.forEach((item) => {
            // 添加事件委托
            item.addEventListener('click', async(event) => {
                let domId = event.target.id

                // 跳转
                if (domId === 'goods-name' || domId === 'goods-img' || domId === 'goods-info' || domId === 'goods-price') {
                    console.log("跳转");
                    window.location.href = `./product_details.html?id=${item.dataset['gid']}`
                }

                // 删除事件
                if (domId === 'close-btn') {
                    let id = item.dataset['id']
                    console.log(id);
                    if (await removeGoods(id)) {
                        item.remove()
                        sumPrice()
                        if (isAllCheck()) {
                            oAllCheckInput.checked = true
                        } else {
                            oAllCheckInput.checked = false
                        }
                    }
                }
            })
        })

        // 下单点击事件
        oCreateOrderBtn.addEventListener('click', async() => {
            let goodsList = []
            let payment = parseFloat(oSumPrice.innerText);

            let oIsCheckedGoods = oGoodsList.querySelectorAll('.ischeck')
            if (oIsCheckedGoods.length === 0) {
                openTip('请选择商品...')
                return
            }
            console.log(oIsCheckedGoods.length);
            oIsCheckedGoods.forEach((item) => {
                let oGoods = item.parentElement
                let id = parseInt(oGoods.querySelector('.goods-num-input').dataset['gid'])
                let num = parseInt(oGoods.querySelector('.goods-num-input').value)
                let name = oGoods.querySelector('#goods-name').innerText
                let type = oGoods.querySelector('#goods-info').innerText
                let price = oGoods.querySelector('#goods-price').innerText
                let img = oGoods.querySelector('#goods-img').src
                    // goodsList.push({
                    //     id: id,
                    //     name: name,
                    //     num: num,
                    //     type: type,
                    //     price: price,
                    //     img: img,
                    // })
                goodsList.push(id)
            })
            sessionStorage.setItem('confirmOrderGoods', JSON.stringify({
                payment: payment,
                goodsList: goodsList
            }))

            console.log(JSON.parse(sessionStorage.confirmOrderGoods))
            location.href = `./confirm_order.html`
        })
    }

    /**
     * @description: 多个商品提交订单
     * @return {*}
     * @param {*} payment 支付金额,小数点至2位;
     * @param {*} addressId 收货地址id;
     * @param {*} goodsList 商品数组,包含每一个商品的id,数量，例：[{id:15,num:1},{id:16,num:2}];
     */
    async function createOrder(payment, addressId, goodsList) {
        let result = false
        await axios.post('/order/create', {
            payment: payment,
            addressId: addressId,
            goodsList: goodsList,
        }).then((resp) => {
            result = resp.status
            console.log(resp);
        })
        return result
    }

    /**
     * @description: 移除商品
     * @return {*}
     * @param {*} id (Number) 购物车条目id;
     */
    async function removeGoods(id) {
        let result = false
        await axios.post('/cart/remove', {
            id: id,
        }).then((resp) => {
            console.log(resp);
            result = resp.status;
            openTip(resp.msg)
        })
        return result
    }

    /**
     * @description: 减少商品数
     * @return {*}
     * @param {*} id (Number) 购物车条目id;
     */
    async function decreaseGoods(id) {
        let result = false
        await axios.post('/cart/decrease', {
                id: id,
            })
            .then(resp => {
                result = resp.status
                console.log(resp);
                if (!resp.status) {
                    openTip(resp.msg)
                }
            })
        return result
    }

    /**
     * @description: 增加商品数
     * @return {*}
     * @param {*} id (Number) 购物车条目id;
     * @param {*} gid (Number) 商品id;
     */
    async function increaseGoods(id, gid) {
        let result = false
        await axios.post('/cart/increase', {
                id: id,
                gid: gid,
            })
            .then(resp => {
                result = resp.status
                console.log(resp);
            })
        return result
    }

    /**
     * @description: 弹出提示框
     * @return {*}
     * @param {*} text (String) 提示内容
     */
    // function openTip(text) {
    //     oTip.style.display = 'inline-block'
    //     oTip.innerText = text
    //     setTimeout(() => {
    //         oTip.style.display = 'none'
    //     }, 3000)
    // }

    /**
     * @description: 计算总价格并刷新
     * @return {*}
     */
    function sumPrice() {
        let sum = 0
        let oCheckInput = document.querySelectorAll('.goods-check.ischeck')
        oCheckInput.forEach((element) => {
            let num = parseFloat(element.parentElement.querySelector('.goods-num-input').value)
            let price = parseFloat(element.parentElement.querySelector('.price span').innerText)
            sum += num.toFixed(2) * price.toFixed(2)
        })
        oSumPrice.innerText = sum.toFixed(2)
    }

    /**
     * @description: 减少数量点击事件
     * @return {*}
     */
    async function reduceNum() {
        let oNumInput = this.event.target.nextElementSibling;
        if (oNumInput.value <= 1) return
        let id = parseInt(oNumInput.dataset['id'])
        if (await decreaseGoods(id)) {
            oNumInput.value--;
            sumPrice()
        } else {
            openTip('减少失败')
        }

    }

    /**
     * @description: 增加数量点击事件
     * @return {*}
     */
    async function plusNum() {
        let oNumInput = this.event.target.previousElementSibling;
        let id = parseInt(oNumInput.dataset['id'])
        let gid = parseInt(oNumInput.dataset['gid'])
        if (await increaseGoods(id, gid)) {
            oNumInput.value++;
            sumPrice()
        }

    }

    /**
     * @description: 选择商品
     * @return {*}
     */
    function selectGoods() {
        let oInput = this.event.target
        oInput.classList.toggle('ischeck')
        sumPrice()
        if (isAllCheck()) {
            oAllCheckInput.checked = true
        } else {
            oAllCheckInput.checked = false
        }
    }

    /**
     * @description: 检查是否全选
     * @return {*}
     */
    function isAllCheck() {
        let oGoodsCheck = Array.from(document.querySelectorAll('.goods-check'))
        console.log(oGoodsCheck);
        return oGoodsCheck.every((item) => {
            return item.checked
        })
    }

    /**
     * @description: 商品列表添加至页面
     * @return {*}
     */
    async function initCartList() {
        await goods.forEach((element) => {
            let elementHTML = `<li data-id="${element.id}"  data-gid="${element.goods_id}" class="good">
                <input class="checkbox goods-check" onclick="selectGoods()" value="${element.id}" type="checkbox">
                <img id="goods-img" class="good-img" src="${element.img}" alt="">
                <div class="content" id="goods-content">

                    <div id="goods-name" class="good-name">
                        ${element.name}
                    </div>
                    <div id="goods-info" class="info">1.8M;米白色</div>
                    <div class="price">￥<span  id="goods-price">${element.price}</span></div>

                </div>
                <div class="check-num">
                    <span onclick='reduceNum()'>-</span>
                    <input data-id='${element.id}' data-gid="${element.goods_id}" class='goods-num-input' type="num" disabled name="num" value="${element.goods_num}">
                    <span onclick='plusNum()'>+</span>
                </div>
                <a class="close"><i id="close-btn" data-id="${element.id}"  class="fa fa-times" aria-hidden="true"></i></a>
            </li>`
            oGoodsList.insertAdjacentHTML('beforeend', elementHTML)
        })
    }


    /**
     * @description: 获取购物车所有商品
     * @return {*}
     */
    async function getCartAll() {
        await axios.get('/cart/list', {
            params: {
                pagesize: pagesize,
                pageindex: pageindex,
            }
        }).then(async(resp) => {
            console.log(resp);
            if (resp.data.length != 0) {
                goods = goods.concat(resp.data)
                pageindex++
                await getCartAll()
            } else {
                console.log("全部加载完成");
                total = resp.total
            }
        }).finally(() => {
            oLoading.style.display = 'none'
        })

    }
</script>


</html>